package org.jeecg.modules.jx.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.miniAppCustomerEndPoint.constant.JxRedisConstant;
import org.jeecg.modules.platformMasterEndPoint.entity.JxFoodRepositoryDo;
import org.jeecg.modules.platformMasterEndPoint.entity.JxSysConfigDo;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxFoodRepositoryMapper;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxSysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 当spring context 创建完成后，执行此类中的run方法，spring context创建完成后，所有的bean都已经创建完了，此时可以使用 mybatis和redis的bean的功能了
 */
@Slf4j
@Component
public class InitialDataLoadRunner implements ApplicationRunner {


    @Autowired
    private JxFoodRepositoryMapper jxFoodRepositoryMapper;

    @Autowired
    private JxSysConfigMapper jxSysConfigMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("begin to load food static info from repository, delete flag 0");
        // 1. 从 菜品库 信息表中，加载所有菜品的静态信息
        List<JxFoodRepositoryDo> list = jxFoodRepositoryMapper.selectList(new LambdaQueryWrapper<JxFoodRepositoryDo>().eq(JxFoodRepositoryDo::getDelFlag, 0));
        for (int k = 0 ; k < list.size(); k ++) {
            JxFoodRepositoryDo jxFoodRepositoryDo = list.get(k);
            String key = JxRedisConstant.JX_FOOD_PREFIX + jxFoodRepositoryDo.getId();
            redisUtil.hset(key, "foodId", jxFoodRepositoryDo.getId());
            redisUtil.hset(key, "foodName", jxFoodRepositoryDo.getFoodName());
            redisUtil.hset(key, "foodTypeName", jxFoodRepositoryDo.getFoodTypeName());
            redisUtil.hset(key, "foodImage", jxFoodRepositoryDo.getImage());
            redisUtil.hset(key, "storeId", jxFoodRepositoryDo.getStoreId());
            redisUtil.hset(key, "storeName", jxFoodRepositoryDo.getStoreName());
        }
        log.info("begin to load food static info from repository successfully");

        // 2. 从系统配置表加载全局配置项
        List<JxSysConfigDo> sysConfigs = jxSysConfigMapper.selectList(new LambdaQueryWrapper<JxSysConfigDo>());
        for (int m = 0 ; m < sysConfigs.size(); m ++) {
            JxSysConfigDo sysConfigDo = sysConfigs.get(m);
            redisUtil.hset(JxRedisConstant.JX_SYS_CONFIG_KEY, sysConfigDo.getConfigKey(), sysConfigDo.getConfigValue());
        }

    }
}
